<?php
namespace app\mp\admin;
use app\system\admin\Admin;
use app\common\model\FactoryOutgo as FactoryOutgoModel;
use app\common\service\Sku as SkuService;
use app\common\service\FactoryOutgo as FactoryOutgoService;
class FactoryOutgo extends Admin
{
    protected $hisiModel = 'FactoryOutgo';//模型名称[通用添加、修改专用]
    protected $hisiValidate = 'FactoryOutgo';
    protected $hisiAddScene = '';//添加数据验证场景名
    protected $hisiEditScene = '';//更新数据验证场景名

    public function initialize() {
    	parent::initialize();
    }

    public function index()
    {
		$factoryKV = [0 => '未分配'] + getFactoryKV(true);
    	if ($this->request->isAjax() || $this->request->param('export/d', 0)) {
    		$where      = $data = [];
    		$page       = $this->request->param('page/d', 1);
    		$limit      = $this->request->param('limit/d', 20);
    		$keyword    = $this->request->param('keyword/s');
			$export     = $this->request->param('export/d', 0);
			if ($export) {
    			set_time_limit(0);
    			ini_set('memory_limit', '1024M');
    			$page = 1;
    			$limit = 99999;
    		}
    		$where[]    = ['status', 'eq', 1];
    		if ($keyword) {
    			$where[] = ['name', 'like', "%{$keyword}%"];
    		}
			
    		$order = 'order desc, id desc';
    		$data['data'] = FactoryOutgoModel::where($where)->page($page)->limit($limit)->order($order)->select();
			foreach ($data['data'] as $k => $v) {
				$factoryName=explode(",",$v['factory_ids']);
				$v['factory_name']="";
				foreach ($factoryName as $key => $value) {
					$data['data'][$k]['factory_name'].=arrayGet($factoryKV, $value,'')."  ";
				}
			}
			
			if ($export) {
				foreach ($data['data'] as $key => $value) {
					//已完成订单
					$t = 4;
					$timeRange = [
						'1' => ['s' => strtotime(date('Y-m-d 00:00:00', time())), 'e' => time()],
						'2' => ['s' => strtotime(date('Y-m-d 00:00:00', time()-86400)), 'e' => strtotime(date('Y-m-d 00:00:00', time()))-1],
						'3' => ['s' => strtotime(date("Y-m-d H:i:s",mktime(0, 0 , 0,date("m"),date("d")-date("w")+1,date("Y")))), 'e' => time()],
						'4' => ['s' => strtotime(date("Y-m-d H:i:s",mktime(0, 0 , 0,date("m"),date("d")-date("w")+1-7,date("Y")))), 'e' => strtotime(date("Y-m-d H:i:s",mktime(23,59,59,date("m"),date("d")-date("w")+7-7,date("Y"))))],
						'5' => ['s' => strtotime(date('Y-M-01 00:00:00', time())), 'e' => time()],
						'6' => ['s' => mktime(0,0,0,date('n')-1,1,date('Y')), 'e' => strtotime(date('Y-m-01 00:00:00', time()))-1],
					];
					$whereOver = [];
					$whereOver[] = ['outgo_status', '>', 0];
					//$whereOver[] = ['outgo_over_time', 'between', [$timeRange[$t]['s'], $timeRange[$t]['e']]];
					$whereOver[] = ['factory_outgo_id', '=', $value['id']];
					$listOver = db('order')->where($whereOver)->order('outgo_over_time desc')->select();

					$keyOver = 'list';
					
					$resultOver=[];
					foreach ($listOver as $v) {
						$resultOver[] = [
							'client_ordernum' => $v['client_ordernum'],
							'sku' => $v['sku'],
							'quantity' => $v['quantity'],
							'outgo_time' =>'【发】'.date("n月j日", $v['outgo_time']),
							'outgo_over_time' => '【回】'.date("n月j日", $v['outgo_over_time']),
							'shipment_time' => '【交】'.date("n月j日", $v['shipment_time']-2*86400),
							'factory_name' => arrayGet($factoryKV, $v['factory_id'], ''),
						];						
					}
					$result= $resultOver;
					if(!isset($result)) {
						$result[0]=[
							'client_ordernum' => '',
							'sku' => '',
							'quantity' => '',
							'outgo_time' => '',
							'outgo_over_time' => '',
							'shipment_time' => '',
							'factory_name' => '',
						];
					}
					$value['orderList']=$result;
					
					$data['data'][$key]=$value;
				}
    			$this->_exportXls('外发工厂详情表-' .date('YmdHis'), $data['data']);
    			exit;
    		}
    		$data['count'] = FactoryOutgoModel::where($where)->count('id');
    		$data['code'] = 0;
    		$data['msg'] = '';
    		return json($data);
    	}

    	$assign = [
			'factoryKV'=>$factoryKV
		];
    	return $this->assign($assign)->fetch();
    }
	/**
     * 导出xls
     *
     * @author KING date 2020年08月11日
     *
     * @param string $fileName
     * @param array $data
     */
    private function _exportXls($fileName, $data) {
    	$head = ['编号','外包工厂名称','访问惟一编码','订单编号','件数','发货日期','回货日期','交货日期'];

    	$phpExcel = getExcelObj();
    	$sheet = $phpExcel->setActiveSheetIndex(0);

    	// 表头处理
    	foreach ($head as $k => $v) {
    		$cellKey = getExcelLetter($k);
    		$sheet->getColumnDimension($cellKey)->setWidth(20);
    		$sheet->setCellValue($cellKey . "1", $v);
    		$sheet->getRowDimension(1)->setRowHeight(30);
    		$sheet->getStyle($cellKey . "1")->getFont()->setBold(true);
    		$sheet->getStyle($cellKey . "1")->getAlignment()->setVertical('center');
    		$sheet->getStyle($cellKey . "1")->getFont()->getColor()->setARGB("FF0000FF");
    	}

    	$skuService = new SkuService();
    	require_once env('root_path').'plugins/excel/phpexcel/Classes/PHPExcel/Worksheet/Drawing.php';

    	$row = 2; // 当前行
    	$n = 0;
    	foreach ($data as $k => $v) {
    		if (count($v['orderList']) > 1) {
    			$endCol = $row + count($v['orderList']) - 1;
    			$sheet->mergeCells('A' . $row . ':A' . $endCol);
    			$sheet->mergeCells('B' . $row . ':B' . $endCol);
    			$sheet->mergeCells('C' . $row . ':C' . $endCol);

    		}

    		$sheet->getStyle('A' . $row)->getAlignment()->setVertical('center');
    		$sheet->getStyle('B' . $row)->getAlignment()->setVertical('center');
    		$sheet->getStyle('C' . $row)->getAlignment()->setVertical('center');


    		$sheet->setCellValueExplicit('A' . $row, $v['id'], 's');
    		$sheet->setCellValueExplicit('B' . $row, $v['name'], 's');
    		$sheet->setCellValueExplicit('C' . $row, $v['code'], 's');
    		$sheet->getStyle('C' . $row)->getAlignment()->setWrapText(TRUE);
			
				foreach ($v['orderList'] as $sk => $sv) {
					// 订单号
					$sheet->setCellValueExplicit('D' . $row, $sv['client_ordernum'], 's');

					// sku
					//$sheet->setCellValueExplicit('E' . $row, $sv['sku'], 's');

					// 订单数量
					$sheet->setCellValueExplicit('E' . $row, $sv['quantity'], 's');

					// 发货时间outgo_over_time
					$sheet->setCellValueExplicit('F' . $row, $sv['outgo_time'], 's');
					// 回货时间
					$sheet->setCellValueExplicit('G' . $row, $sv['outgo_over_time'], 's');
					// 交货时间
					$sheet->setCellValueExplicit('H' . $row, $sv['shipment_time'], 's');
					$row++;
				}
				$n++;
			
    		
    	}

    	// Rename worksheet
    	$sheet->setTitle('worksheet');

    	header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
    	header('Content-Disposition: attachment;filename="'.$fileName.'.xlsx"');
    	header('Cache-Control: max-age=0');
    	header('Cache-Control: max-age=1');
    	header ('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT');
    	header ('Cache-Control: cache, must-revalidate');
    	header ('Pragma: public');

    	$objWriter = \PHPExcel_IOFactory::createWriter($phpExcel, 'Excel2007');
    	$objWriter->save('php://output');
    	exit();
    }
	/**
     * 单独编辑外发工厂
     *
     * @author 飞燕 date 2021年04月12日
     *
     * @param array $data
     */
	public function factoryEdit() {
		$id       = $this->request->param('id/d', 0);
		$factoryId       = $this->request->param('factory_id/d', 0);

		$factoryOutgoService=new FactoryOutgoService();
		$foInfo=$factoryOutgoService->getInfoById($id);
		if(!$foInfo)			return $this->error("数据异常");
    	$upData = [
			'factory_id'=>$factoryId,
    		'update_time' => time(),
    	];
    	$ret = db('factory_outgo')->where('id', $id)->update($upData);
    	if ($ret) {
    		return $this->Json(1, '保存信息成功');
    	} else return $this->Json(0);
	}
	/**
     * 编辑
     */
	public function edit() {
		$factoryKV = [0 => '未分配'] + getFactoryKV(true);
		$factoryOutgoService=new FactoryOutgoService();
		$id = $this->request->param('id/d', 0);
    	if ($this->request->isPost()) {// 数据验证
			$factoryIds=$this->request->param('factory_ids', "");	
    		$postData = $this->request->post();
			$postData['factory_ids'] =$factoryIds;	
    		$postData['update_time'] = time();
    		db('factory_outgo')->where('id', $id)->update($postData);
			$factoryOutgoService->updateKVCache();
    		return $this->success('保存成功', '');
    	}
    	$template = $this->request->param('template', 'form');
		$formData = $factoryOutgoService->getInfoById($id);
    	$this->assign('formData', $formData);
    	$assign = [
    		'factoryKV'=>$factoryKV
    	];
    	return $this->assign($assign)->fetch($template);
	}
	/**
     * 添加
     */
    public function add()
    {
		$factoryKV = [0 => '未分配'] + getFactoryKV(true);
		$factoryOutgoService= new FactoryOutgoService();
    	if ($this->request->isPost()) {

    		$factoryIds=$this->request->param('factory_ids', "");	
    		$postData = $this->request->post();
			$postData['factory_ids'] =$factoryIds;
			$code=getRandomString(8);
			$postData['code']=$code;
    		$postData['create_time'] = $postData['update_time'] = time();
    		$id = db('factory_outgo')->insertGetId($postData);
    		if (!$id) {
    			return $this->error('保存失败');
    		}
			$factoryOutgoService->updateKVCache();
    		return $this->success('保存成功', '');
    	}
    	$assign = [
    		'factoryKV'=>$factoryKV
    	];

    	$template = $this->request->param('template', 'form');
    	return $this->assign($assign)->fetch($template);
    }
}